var express = require("express");
var router = express.Router();
let auditAll = require("../model/auditor");

router.get("/manager/fyh", (req, res) => {
  auditAll.homeindexs.find(req, (err, result) => {
    if (!err) {
      res.send({
        errmsg: "成功",
        result: result,
      });
    }
  });
});

// post请求获取列表示例
router.post("/audit/auditRecord", async (req, res) => {
  var obj = req.body;
  let page = parseInt(req.body.pageNum) || 1;
  let limit = parseInt(req.body.pagesize) || 10;
  let skip = (page - 1) * limit;
  for (let i in obj) {
    let val = new RegExp(obj[i]);
    obj[i] = val;
  }
  try {
    let result = await auditAll.auditrLists
      .find(obj)
      .skip(skip)
      .limit(limit)
      .exec();

    let total = await auditAll.auditrLists.countDocuments();
    setTimeout(() => {
      res.send({
        errmsg: "成功",
        result: true,
        list: result,
        // currentPage: page,
        // totalPages: Math.ceil(total / limit),
        totalCount: total,
      });
    }, 1500);
  } catch (err) {
    res.send({
      errmsg: "失败",
      result: false,
    });
  }
});

// 新增
router.post("/audit/auditAdd", (req, res) => {
  var obj = req.body;
  auditAll.auditrLists.create(obj, (err, result) => {
    if (!err) {
      res.send({
        errmsg: "新增成功",
        result: true,
        list: result,
      });
    } else {
      res.send({
        errmsg: "失败",
        result: false,
      });
    }
  });
});

// 修改
router.post("/audit/auditEdit", (req, res) => {
  var obj = req.body;
  auditAll.auditrLists.findOneAndUpdate(
    { _id: obj._id },
    obj,
    (err, result) => {
      if (!err) {
        res.send({
          errmsg: "修改成功",
          result: true,
          list: result,
        });
      } else {
        res.send({
          errmsg: "失败",
          result: false,
        });
      }
    }
  );
});

// 删除
router.post("/audit/auditDel", async (req, res) => {
  var obj = req.body;
  try {
    let result = await auditAll.auditrLists.deleteMany({
      _id: { $in: obj.ids },
    });
    res.send({
      errmsg: "删除成功",
      result: true,
      list: result,
    });
  } catch (err) {
    res.send({
      errmsg: "失败",
      result: false,
    });
  }
});

module.exports = router;
